package memory;
import javax.swing.JPanel; 
import javax.swing.border.EtchedBorder;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.Serializable;


@SuppressWarnings("serial")
public class PlayerPanel extends JPanel implements Serializable {
	
	private Player[] playerArray;
	private int nrPlayers;
	private int currentPlayer;
	
	public PlayerPanel( String[] playerNames ) {
		playerArray = Tools.createPlayers( playerNames );
		nrPlayers = playerArray.length;
		
		selectRandomPlayer();
		createPanel();	
	}
	
	//This is needed in net games for the id's to be the same everywhere
	public PlayerPanel( Player[] p ) {
		playerArray = p;
		nrPlayers = playerArray.length;
		
		selectRandomPlayer();
		createPanel();
	}
	
	private void selectRandomPlayer() {
		//Select a random player to start playing
		int randomPlayer;
		if (nrPlayers > 1) {
			randomPlayer = Tools.getRandomNr(Options.getNrOfPlayers()-1);
		}
		else {
			randomPlayer = 0;
		}
		
		setCurrentPlayer(randomPlayer);
	}
	
	//"Create" the new playerpanel and add all the players to it.
	private void createPanel() {
	
		//Create grid and add the players to it.
		this.setLayout( new GridLayout( 1, nrPlayers ) );
		this.setPreferredSize( new Dimension( 800, 50 ) );
		
		EtchedBorder e = new EtchedBorder();
						
		for( int i = 0 ; i < nrPlayers ; i++ ) {
			playerArray[i].setBorder(e);
			this.add( playerArray[i] );
		}
		
	}
	
	public Player getPlayer(int nr) {
		return playerArray[ nr ];
	}
	
	public Player getCurrentPlayer() {
		return getPlayer( currentPlayer );
	}
	
	public void setCurrentPlayer(int nr) {
		currentPlayer = nr;
		
		for( int i = 0 ; i < 4 ; i++ ) {
			try {
				getPlayer(i).setBackground(null);
			}
			catch( Exception e) {}
		}
		
		getCurrentPlayer().setBackground(Color.PINK);
	}
	
	public void setCurrentPlayer(Player p) {
		int i = 0;
		while(getPlayer(i) != p) {
			i++;
		}
		setCurrentPlayer(i);
	}
	
	public void nextPlayer() {
		//Set current players color to grey
		getPlayer(currentPlayer).setBackground(null);
		
		//Change player
		if(currentPlayer == (nrPlayers - 1)) {
			currentPlayer = 0;
		}
		else {
			currentPlayer++;			
		}
		
		//Change new players background to pink
		getPlayer(currentPlayer).setBackground(Color.PINK);
		
	}
	
	//Replace the old player with a copy of the new but with the score increased
	public void updatePlayer(Player fromServer) {
		//Find the player corresponding to our own. Use the ID as identifier.
		int i = 0;
		while( getPlayer(i).getID() != fromServer.getID() ) {
			i++;
		}
		
		playerArray[i] = fromServer;		
	}
	
	public int nrOfPlayers() {
		return nrPlayers;
	}
	
}
